<template>
  <BaseTable
    ref="baseTableRef"
    :apiUrl="getNetworkList"
    :rowId="curTab"
    :otherQuery="{ orderByColumn: 'create_time' }"
    isChangeColumns
    :placeholder="`请输入${curTab === 'network-vpc' ? '名称' : '名称/CIDR/网关'}`"
    :columns="curTab === 'network-vpc' ? vpccolumns : subcolumns"
    :height="height"
    :isRowSelection="menu === 'cluster'"
    @handleSelectionChange="(val) => (selectedKeys = val)"
    :isShowAddBtn="false"
  >
    <template #operatBtns>
      <ga-button
        v-if="menu"
        type="primary"
        style="margin: 0 8px"
        @click="
          $refs?.[`${curTab === 'network-vpc' ? 'addVpcRef' : 'addSubnetRef'}`]?.open()
        "
        >创建
      </ga-button>
      <ga-button
        v-if="menu === 'cluster'"
        :type="isdisable ? 'secondary' : 'primary'"
        status="danger"
        :disabled="isdisable"
        @click="handleDelete(selectedKeys)"
      >
        删除
      </ga-button>
    </template>
    <template #filterOpt>
      <ga-select
        v-if="curTab !== 'network-vpc' && !menu"
        style="width: 280px; margin-left: 8px"
        placeholder="选择VPC"
        allow-clear
        @clear="$refs.baseTableRef.fetchData()"
      >
        <ga-option
          v-for="(item, idx) in networkList"
          :key="idx"
          :label="item.name"
          @click="
            $refs.baseTableRef.fetchData({
              network_uuid: item.uuid,
              resourceId: item.resourceId,
            })
          "
          :value="item.id"
        />
      </ga-select>
      <ga-cascader
        v-if="curTab === 'network-vpc' && !menu"
        allow-clear
        check-strictly
        path-mode
        :field-names="{ value: 'tableId', label: 'name' }"
        :options="platformOptions"
        style="width: 280px; margin-left: 8px"
        placeholder="选择平台/集群"
        @change="handleChange"
      />
    </template>
    <template #action="{ record }" v-if="menu === 'cluster'">
      <!-- <ga-link :loading="syncLoading" @click="handleSync(record)">同步</ga-link> -->
      <ga-link status="danger" @click="handleDelete([record?.id])">删除</ga-link>
    </template>
  </BaseTable>
  <addVpc ref="addVpcRef" @fetchData="$refs.baseTableRef.fetchData()" />
  <addSubnet ref="addSubnetRef" @fetchData="$refs.baseTableRef.fetchData()" />
</template>

<script setup>
import { ref, watch, onMounted, h, computed, reactive } from "vue";
import { render } from "@/utils";
import { useRoute } from "vue-router";
import LinkText from "@/components/LinkText/index.vue";
import {
  getNetworkList,
  deleteNetwork,
  syncNetwork,
  getPlatformTreeList,
} from "@/api/network";
import { warningModal } from "@/hooks/useWarningModal";
import { Message } from "@garco-design/web-vue";
import addVpc from "./addVpc.vue";
import addSubnet from "./addSubnet.vue";
const platformOptions = ref([]);
// 网络类型 vpc or subnet
const props = defineProps({
  netType: {
    type: String,
    default: "",
  },
  height: {
    type: String,
    default: "calc(100vh - 236px)",
  },
});
const route = useRoute();
const syncLoading = ref(false);
const baseTableRef = ref(null);
const { tab, menu, type, uuid } = route.query;
const selectedKeys = ref([]);
const isdisable = computed(() => selectedKeys.value?.length === 0);
// 多选方法
const curTab = ref(tab || props.netType);
watch(
  () => route.query,
  (newValue, oldValue) => {
    curTab.value = newValue.tab;
    if (newValue.tab === oldValue.tab) {
      baseTableRef.value.fetchData();
    }
  }
);
// 处理方法
const handleChange = (val) => {
  const obj = {};
  if (val.length === 1) {
    obj.resourceId = val[0];
  } else {
    const options = platformOptions.value || [];
    const cur = options.find((item) => val.includes(item.tableId));
    if (cur) {
      obj.resourceId = cur.tableId;
      const firstChild = Array.isArray(cur.children) ? cur.children[0] : undefined;
      obj.clusterUuid = firstChild?.clusterUuid;
    }
  }
  baseTableRef.value.fetchData(obj);
};
// 查询树-平台&集群
const handlePlatformTreeList = async () => {
  syncLoading.value = true;
  try {
    const { code, data } = await getPlatformTreeList();
    if (code === 20000) platformOptions.value = data;
  } catch (err) {
    console.log(err);
  }
};
// 处理同步方法
const handleSync = async () => {
  syncLoading.value = true;
  try {
    const { code } = await syncNetwork(curTab.value);
    if (code === 200) Message.success("同步成功");
  } finally {
    syncLoading.value = false;
  }
};
// 处理方法
const networkList = ref([]);
const fetchNetworkData = async () => {
  try {
    const { code, data } = await getNetworkList({ limit: -1 }, "network-vpc");
    if (code === 20000) networkList.value = data.items;
  } catch (error) {}
};
// 处理删除方法
const handleDelete = async (records) => {
  // console.log(records);
  // console.log("type", type);
  const ids = records.map((item) => ({
    id: item,
    clusterUuid: type === "vmware" ? uuid : "",
  }));
  console.log("ids", ids);

  warningModal(`确定要删除数据吗`, async () => {
    try {
      const { code } = await deleteNetwork(curTab.value, ids);
      if (code === 20000) Message.success("操作成功");
      baseTableRef.value.fetchData();
    } catch (err) {
      console.log(err);
    }
  });
};
// excelDownload() {
//       this.downloadLoading = true
//       hostPage(this.listQuery).then(response => {
//         import('@/utils/Export2Excel').then(excel => {
//           const tHeader = ['名称', '可用域', 'vCPU（已用）', 'vCPU（总计）', '已消耗CPU占比', '内存（已用）', '内存（总计）', '已消耗内存占比', '实例']
//           const filterVal = ['name', 'clusterId', 'vmCoreKernel', 'cpuSupe', 'cpuPercentage', 'vmRamBit', 'ramSupe', 'memPercentage', 'totalVmCount']
//           const { content } = response
//           const list = content.rows
//           const data = this.formatJson(filterVal, list)
//           excel.export_json_to_excel({
//             header: tHeader,
//             data,
//             filename: 'HostList',
//             autoWidth: true,
//             bookType: this.bookType
//           })
//           this.downloadLoading = false
//         })
//       })
//     },
//     formatJson(filterVal, jsonData) {
//       return jsonData.map(v =>
//         filterVal.map(j => {
//           if (j === 'cpuPercentage') {
//             return this.cpuPercentage(v) + '%'
//           } else if (j === 'memPercentage') {
//             return this.memPercentage(v) + '%'
//           } else if (j === 'ramSupe' || j === 'vmRamBit') {
//             return (v[j] || 0) + ' GB'
//           } else if (j === 'vmCoreKernel') {
//             return v[j] || 0
//           } else {
//             return v[j]
//           }
//         })
//       )
//     }
onMounted(() => {
  if (!menu) {
    if (curTab.value === "network-vpc") handlePlatformTreeList();
    else fetchNetworkData();
  }
});
import ipPool from "../../../layer2subnet/components/ipPool.vue";
const vpccolumns = [
  {
    title: "名称",
    dataIndex: "name",
    tooltip: true,
    ellipsis: true,
    width: 220,
    fixed: "left",
    render,
  },
  {
    title: "子网数量",
    dataIndex: "networkSubnetNum",
    tooltip: true,
    ellipsis: true,
    width: 100,
    render,
  },
  {
    title: "虚拟机数量",
    dataIndex: "vmNum",
    width: 160,
    render,
  },
  {
    title: "关联宿主机数量",
    dataIndex: "hostNum",
    width: 160,
    tooltip: true,
    ellipsis: true,
    render,
  },
  {
    title: "网络类型",
    dataIndex: "type",
    width: 160,
    tooltip: true,
    ellipsis: true,
    render,
  },
  {
    title: "vlanId",
    dataIndex: "vlanId",
    width: 160,
    tooltip: true,
    ellipsis: true,
    render,
  },
  {
    title: "创建信息",
    dataIndex: "lastTime",
    slotName: "lastTime",
    width: 180,
    render: ({ record }) =>
      h(LinkText, { label: record?.createTime, desc: record?.createBy }),
  },
  {
    title: "变更信息",
    dataIndex: "lastTime",
    slotName: "lastTime",
    width: 180,
    render: ({ record }) =>
      h(LinkText, { label: record?.updateTime, desc: record?.updateBy }),
  },
  {
    title: "操作",
    width: 80,
    fixed: "right",
    dataIndex: "action",
    slotName: "action",
  },
];
const subcolumns = [
  {
    title: "名称",
    dataIndex: "name",
    width: 200,
    tooltip: true,
    ellipsis: true,
    fixed: "left",
    render,
  },
  {
    title: "CIDR",
    dataIndex: "cidr",
    tooltip: true,
    ellipsis: true,
    width: 150,
    render,
  },
  {
    title: "VPC",
    dataIndex: "networkName",
    width: 200,
    render,
  },
  {
    title: "地址池",
    dataIndex: "ipPools",
    render: ({ record }) => h(ipPool, { list: record?.ipPools || [] }),
    width: 240,
  },
  {
    title: "网关",
    dataIndex: "gateway",
    tooltip: true,
    ellipsis: true,
    width: 150,
    render,
  },
  {
    title: "DNS",
    dataIndex: "dns1",
    tooltip: true,
    ellipsis: true,
    width: 170,
    render: ({ record }) =>
      h("div", [
        h("p", `dns1：${record?.dns1 || "-"}`),
        h("p", `dns2：${record?.dns2 || "-"}` || "-"),
      ]),
  },
  {
    title: "DHCP",
    dataIndex: "dhcp",
    tooltip: true,
    ellipsis: true,
    width: 170,
    render,
  },
  {
    title: "创建信息",
    dataIndex: "lastTime",
    slotName: "lastTime",
    width: 180,
    render: ({ record }) =>
      h(LinkText, { label: record?.createTime, desc: record?.createBy }),
  },
  {
    title: "变更信息",
    dataIndex: "lastTime",
    slotName: "lastTime",
    width: 180,
    render: ({ record }) =>
      h(LinkText, { label: record?.updateTime, desc: record?.updateBy }),
  },
  {
    title: "操作",
    width: 80,
    dataIndex: "action",
    fixed: "right",
    slotName: "action",
  },
];
</script>

<style lang="scss" scoped></style>
